import { getToken, removeToken } from './auth'

interface RequestOptions {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  data?: any
  header?: any
}

class Http {
  private baseUrl: string

  constructor() {
    this.baseUrl = 'https://api.example.com' // 替换为实际的API地址
  }

  private async request<T>(options: RequestOptions): Promise<T> {
    const token = getToken()
    const header = {
      'Content-Type': 'application/json',
      ...options.header,
    }

    if (token) {
      header['Authorization'] = `Bearer ${token}`
    }

    try {
      const response = await uni.request({
        url: this.baseUrl + options.url,
        method: options.method || 'GET',
        data: options.data,
        header,
      })

      const [error, res] = response

      if (error) {
        throw new Error(error.errMsg)
      }

      // 处理HTTP状态码
      if (res.statusCode === 401) {
        // token过期或无效
        removeToken()
        uni.redirectTo({ url: '/pages/login/index' })
        throw new Error('请重新登录')
      }

      if (res.statusCode >= 400) {
        throw new Error(res.data.message || '请求失败')
      }

      return res.data as T
    } catch (error) {
      uni.showToast({
        title: error.message || '网络错误',
        icon: 'none',
      })
      throw error
    }
  }

  get<T>(url: string, data?: any) {
    return this.request<T>({
      url,
      method: 'GET',
      data,
    })
  }

  post<T>(url: string, data?: any) {
    return this.request<T>({
      url,
      method: 'POST',
      data,
    })
  }

  put<T>(url: string, data?: any) {
    return this.request<T>({
      url,
      method: 'PUT',
      data,
    })
  }

  delete<T>(url: string, data?: any) {
    return this.request<T>({
      url,
      method: 'DELETE',
      data,
    })
  }
}

export const http = new Http()
